﻿
//修改文本框  但未保存
$('input,textarea,select').change(function () {
    sessionStorage.setItem('alertSave', true);
    sessionStorage.setItem('isFirst', true);
})

//标题编辑
function clickEdictTitle(ele, tipsEle) {
    $(tipsEle).addClass('inputShadow');
}

//背景图编辑
function clickEdictBg(ele) {
    $("#ModalImg").prop("src", $(ele).attr("src"));
    UpImg(ele);
}

function clickEdict(ele) {
    $(ele).siblings('div').removeClass('clickEdict-border').find('.clickEdict').css('display', 'none');
    $(ele).toggleClass('clickEdict-border').find('.clickEdict').toggle();
    if ($(ele).hasClass('clickEdict-border')) {
        $(ele).attr('title', '再次点击可取消编辑');
    }
    else {
        $(ele).attr('title', '点击可编辑');
    }
}
function changeIMG(ele) {
    $("#ModalImg").prop("src", $(ele).next().attr("src"));
    UpImg($(ele).next());
}
function changeEggsIMG(ele) {
    $("#ModalImg").prop("src", $(ele).next().find("img").attr("src"));
    UpImg($(ele).next().find("img"));
}

//九宫格编辑
function changeNineIMG(ele) {
    $("#tableGo").prop("src", $(ele).next().find("#go").attr("src"));
    $("#tableImg0").prop("src", $(ele).next().find(".img0").attr("src"));
    $("#tableImg1").prop("src", $(ele).next().find(".img1").attr("src"));
    $("#tableImg2").prop("src", $(ele).next().find(".img2").attr("src"));
    $("#tableImg3").prop("src", $(ele).next().find(".img3").attr("src"));
    $("#tableImg4").prop("src", $(ele).next().find(".img4").attr("src"));
    $("#tableImg5").prop("src", $(ele).next().find(".img5").attr("src"));
    $("#tableImg6").prop("src", $(ele).next().find(".img6").attr("src"));
    $("#tableImg7").prop("src", $(ele).next().find(".img7").attr("src"));
    $("#tableImg8").prop("src", $(ele).next().find(".img8").attr("src"));
    UpImg(ele)
}

//界面上传图片
var uploader110;
function UpImg(el) {
    if (!uploader110) {
        uploader110 = WebUploader.create({
            // swf文件路径
            swf: '~/Scripts/WebUploader/Uploader.swf',
            // 文件接收服务端。
            server: '/DBH/UploadImgToOSS_DataName',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: {
                id: '#lak',
                //id: selector,
                multiple: false
            },
            accept: {
                title: '图片',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
            },
            threads: 1, //上传并发数
            disableGlobalDnd: true,
        });
        uploader110.on('uploadError', function (file, r) {
            $.L.msgWarning("上传出错！");
        });
        uploader110.on('error', function (r) {
            $.L.msgError("格式有误,请上传图片文件！");
        })
        uploader110.on('uploadComplete', function (file) {
            $('#' + file.id).remove();
        });
    }
    for (var i = 0; i < uploader110._events.length; i++) {
        var _event_temp = uploader110._events[i];
        if (_event_temp) {
            if (_event_temp.e == "fileQueued" ||
                _event_temp.e == "uploadProgress" ||
                _event_temp.e == "uploadSuccess") {
                uploader110._events.splice(i, 1);
                i--;
            }
        }
    }
    // 当有文件被添加进队列的时候
    uploader110.on('fileQueued', function (file) {
        $('#showImg').append('<div id="' + file.id + '" >' +
       '<p class="state">等待上传...</p>' +
   '</div>');
        uploader110.upload();
    });

    // 文件上传过程中创建进度条实时显示。
    uploader110.on('uploadProgress', function (file, percentage) {
        var $li = $('#' + file.id),
            $percent = $li.find('.progress .progress-bar');
        // 避免重复创建
        if (!$percent.length) {
            $percent = $('<div class="progress progress-striped active">' +
              '<div class="progress-bar" role="progressbar" style="width: 0%">' +
              '</div>' +
            '</div>').appendTo($li).find('.progress-bar');
        }
        $li.find('p.state').text('上传中');
        $percent.css('width', percentage * 100 + '%');
    });

    uploader110.on('uploadSuccess', function (file, response) {
        $('#ModalImg').attr('src', response._raw);
        $('.clickEdict-border').removeClass('clickEdict-border').find('.clickEdict').css('display', 'none');
        $(el).attr("src", response._raw);
        
        if ($(el).attr('id') == 'companyLogo')
        {
            $('#LogoImgUrl').attr("src", response._raw);
        }
        if ($(el).attr('id') == 'PublicCode')
        {
            $('#Upload_WXCodeImgUrl').attr("src", response._raw);
        }
        $.L.msgSuccess('上传成功！');
    });
}

//表单上传图片
function UpLittleImg(selector) {

    var uploader1 = WebUploader.create({
        // swf文件路径
        swf: '~/Scripts/WebUploader/Uploader.swf',
        // 文件接收服务端。
        server: '/DBH/UploadImgToOSS_DataName',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: {
            id: selector,
            multiple: false
        },
        accept: {
            title: '图片',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'img/*'
        },
        threads: 1, //上传并发数
        disableGlobalDnd: true,
    });
    uploader1.on('uploadError', function (file, r) {
        $.L.msgWarning("上传出错！");
    });
    uploader1.on('error', function (r) {
        $.L.msgError("格式有误,请上传图片文件！");
    })
    uploader1.on('uploadComplete', function (file) {
        $('#' + file.id).remove();
    });
    // 当有文件被添加进队列的时候
    uploader1.on('fileQueued', function (file) {
        uploader1.upload();
    });
    uploader1.on('uploadSuccess', function (file, response) {
        $(selector).next().val(response._raw).parent().prev().attr("src", response._raw);
        if (selector == '#companyPublicCode') {
            $('#QRcode').attr("src", response._raw);
        }
        if (selector == '#logoUp') {
            $('#companyLogo').next().attr("src", response._raw);
        }
        if (selector == '#weixinCode') {
            $('#companyWeixinCode').attr("src", response._raw);
        }
        if (selector == '#awardsUp') {
            $('#awardsUpCode').attr("src", response._raw);
        }
        $.L.msgSuccess('上传成功！');
    });
}
UpLittleImg('#logoUp');//上传企业logo
UpLittleImg('#awardsUp');//上传奖品详情模块微信公众号
UpLittleImg('#weixinCode');//上传没中奖，或 奖品被领取的模块 微信公众号
UpLittleImg('#LoadingUp');//上传loading图片
UpLittleImg('#companyPublicCode');//上传企业微信二维码




//九宫格 
//1:上传图片按钮
//2:替换图片
//3.文本框图片保存路径
function UpAwardsListImg(selector, imgele, valId) {
     
    var uploader1 = WebUploader.create({
        // swf文件路径
        swf: '~/Scripts/WebUploader/Uploader.swf',
        // 文件接收服务端。
        server: '/DBH/UploadImgToOSS_DataName',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: {
            id: selector,
            multiple: false
        },
        accept: {
            title: '图片',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'img/*'
        },
        threads: 1, //上传并发数
        disableGlobalDnd: true,
    });
    uploader1.on('uploadError', function (file, r) {
        $.L.msgWarning("上传出错！");
    });
    uploader1.on('error', function (r) {
        $.L.msgError("格式有误,请上传图片文件！");
    })
    uploader1.on('uploadComplete', function (file) {
        $('#' + file.id).remove();
    });
    // 当有文件被添加进队列的时候
    uploader1.on('fileQueued', function (file) {
        uploader1.upload();
    });
    uploader1.on('uploadSuccess', function (file, response) {
        $(imgele).attr("src", response._raw);
        $(valId).val(response._raw);
        $.L.msgSuccess('上传成功！');
    });
}
//抽奖按钮、谢谢参与、奖项一上传图片
UpAwardsListImg("#loadGo", "#tableGo,#go");
UpAwardsListImg("#loadImg0", "#tableImg0,.img0", "#AwardsIosUrl0");
UpAwardsListImg("#loadImg1", "#tableImg1,.img1", "#AwardsIosUrl1");


//奖项图片上传
function UpAwardsInit() {
    for (var i = 1; i <=8; i++) {
        //var par2 = "#tableImg" + i + ",.img" + i;
        //var par3 = "#AwardsIosUrl" +parseInt( i+1);
        ////奖项奖品图片
        //UpAwardsListImg("#loadImg" + i, par2, par3);
        //奖项 一键关注  二维码上传 
        UpAwardsListImg("#awardsUp"+i, "#awardsUpImg"+i, "#WxCodeImg"+i);
    }
}
UpAwardsInit();


//批次下拉框绑定数据
function Ajax_BatchBox(batch)
{
    $("#batchInput").val(batch);
    batch = batch.split(',') || 0;
    $.L.ajaxHandle({
        url: ACTION_URL("GetBatchList", "Market") + "?batchID=" + batch,
        success: function (data) {
            $("#batch").html("");
            var $option = "";
            var BatchNum = 0;
            $(data).each(function (i, obj) {
                $(batch).each(function (x, ele) {
                    if (ele == obj.Batch) { 
                    BatchNum += obj.Gen_Code_Nums;
                }
                })
                    $option += "<option value='" + obj.Batch + "' num='" + obj.Gen_Code_Nums + "'>" + obj.Batch + "</option>";
            })
            $("#batch").attr('multiple', 'multiple').html($option);
            $("#batch").selectpicker('refresh');
            $('#batch').selectpicker('val', batch);
            $('#batchNum').text(BatchNum);
            //$('#batch').next().find('#batchNum').text($("#batch").val());
        }
    });
}
Ajax_BatchBox('@Model.activity.Batch');
//改变显示生码批次的数据
function ChangeBatchNum(obj) {
    var num = 0;
    var batch = "";
    if ($("#batch option:selected").attr('Num')!=undefined) {
        for (var i = 0; i < $("#divBatch .selected a .text").length; i++) {
            num += parseInt($("#batch option[value='" + $("#divBatch .selected a .text").eq(i).text() + "']").attr("num"));
            batch += $("#divBatch .selected a .text").eq(i).text() + ",";
        }
    }
    $('#batchNum').text(num);
    $('#batchInput').val(batch);
    $("#Rate").val("")
    $("#TotalNums").val("")
};


//限制区域 加载省市
function Privance(BigPlaceId, ids, cityIds) {
    $.ajax({
        type: "POST",
        url: "Manager/GetPrivance?id=0" + "&ids=" + ids,
        success: function (data) {
            var htmlsel = '';
            $("#" + BigPlaceId).children().remove();
            $.each(data, function (i, item) {
                if (item.Selected) {
                    htmlsel += "<option  selected value='" + item.Value + "'>" + item.Text + "</option>";
                }
                else {
                    htmlsel += "<option  value='" + item.Value + "'>" + item.Text + "</option>";
                }
            });
            $("#" + BigPlaceId).attr('multiple', 'multiple').append(htmlsel);
            $("#" + BigPlaceId).selectpicker();
            $("#" + BigPlaceId).selectpicker('refresh');
            if (BigPlaceId == "Privance") {
                Choose('Privance', 'City', cityIds)
            } 
        }
    });
}
Privance("Privance", "@Model.activity.Privance", "@Model.activity.City");
//选择省市
function Choose(BigPlaceId, SmallPlaceId, ids) {
    var id = $("#" + BigPlaceId).val();
    $.ajax({
        type: "POST",
        url: "Manager/GetPrivance?id=" + id + "&ids=" + ids,
        success: function (response) {
            var htmlsel = '';
            $("#" + SmallPlaceId).children().remove();
            $.each(response, function (i, item) {
                if (item.Selected) {
                    htmlsel += "<option  selected value='" + item.Value + "'>" + item.Text + "</option>";
                }
                else {
                    htmlsel += "<option  value='" + item.Value + "'>" + item.Text + "</option>";
                }
            });
            $("#" + SmallPlaceId).attr('multiple', 'multiple').append(htmlsel);
            $("#" + SmallPlaceId).selectpicker({});
            $("#" + SmallPlaceId).selectpicker('refresh');
        }
    });
}




/// val 0 隐藏 1 显示   ele 选择器
function IsShow(val,ele)
{
    if (val==0)  
    {
      $(ele).hide();
    }
    else
    {
        $(ele).show();
    }
}

function IsShow(val, ele, ele2)
{
    if (val == 0) {
        $(ele).hide();
        $(ele2).show();
        if (ele2 == "#rollInfo,.rollInfoTxt") {
            $("#awardInfoDefault").prop("checked", true);
            $("#awardInfoDefine").prop("checked",false);
        }
        else {
            $("#gameTimeDefault").prop("checked", true);
            $("#gameTime").prop("checked",false);
        }
    }
    else {
        $(ele).show();
        $(ele2).hide();
        if (ele2 == "#rollInfo,.rollInfoTxt") {
            $("#awardInfoDefine").prop("checked", true);
            $("#awardInfoDefault").prop("checked",false);
        }
        else {
            $("#gameTime").prop("checked", true);
            $("#gameTimeDefault").prop("checked",false);
        }
    }
}


 //详细数据
function ShowHideBtn(ele) {
    $(ele).parent().parent().next('.toggle-panal').toggle();

    //if($('#JackpotType0').val()=='1')
    //{
    //    $('.form-group.vailTime').css('display', 'none');
    //}
    //else {
    //    $('.form-group.vailTime').css('display', 'block');
    //}
}



//点击领取按钮出现效果
//$('#clickRequest').click(function () {
//    $(this).next('.bg-con').css('display', 'block').children('.small-bg').children('p:nth-child(1)').addClass('animated bounceInLeft');
//    $(this).next('.bg-con').children('.small-bg').children('a.add').addClass('animated  zoomIn');
//})
//$('.confirm').click(function () {
//    $(this).next('.bg-con').css('display', 'block').children('.small-bg').children('p:nth-child(1)').addClass('animated bounceInLeft');
//    $(this).next('.bg-con').children('.small-bg').children('a.add').addClass('animated  zoomIn');
//})

function showResult(ele) {
    $(ele).parent().next('.bg-con').css('display', 'block');
    $(ele).parent().next('.bg-con').find('.closeBgCon').click(function () {
        $(this).parent().hide();
    });
}

//可拖可拽
$('.resizable.draggable').resizable({
    containment: 'parent',
    stop: function (e, ui) {
        var parentW = $(this).parent().width();
        var parentH = $(this).parent().height();
        var _thisW = $(this).width();
        var _thisH = $(this).height();
        var left = parseInt($(this).css('left'));
        var top = parseInt($(this).css('top'));
     
        $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
    }
});
$('.resizable.draggable').draggable({
    containment: 'parent',
    stop: function () {
        var parentW = $(this).parent().width();
        var parentH = $(this).parent().height();
        var _thisW = $(this).width();
        var _thisH = $(this).height();
        var left = parseInt($(this).css('left'));
        var top = parseInt($(this).css('top'));
        $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
    }
});
$('.draggable').draggable({
    containment: 'parent',
    stop: function () {
        var parentW = $(this).parent().width();
        var parentH = $(this).parent().height();
        var _thisW = $(this).width();
        var _thisH = $(this).height();
        var left = parseInt($(this).css('left'));
        var top = parseInt($(this).css('top'));
        $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
    }
});

var boxValArr = [];
$.MGJ.TableEggsActivity = [];
(function () {
    $.extend($.MGJ.TableEggsActivity, {
        //获取奖项数量 
        GetAwardNum: function (index) {
            var id = "#JackpotID" + index;
            var idNum = "#JackepotNum" + index;
            $(idNum).text($(id + " option:selected").data("num"));
            if ($(idNum).text() == "0") {
                $("#TotalNums" + index).val(0);
                $("#Rate" + index).val(0);
            }
            //清空数组
            boxValArr = [];
            //重新赋值
            for (var i = 1; i <= pageCount; i++) {
                var a = $("#JackpotID" + i + " option:selected").val();

                boxValArr.push($("#JackpotID" + i).val());
            }
            $("#TotalNums" + index).removeAttr("readonly");
        },
        //获取下拉框奖项  检查类型   //红包默认显示    //数量默认显示
        //奖项类型  奖项索引  下拉框选中的索引  操作类型 add || edit 
        GetAward: function (type, index, boxVal, oper) {
           
            boxVal = boxVal || 0;
            var id = "#JackpotID" + index;
            $(id).html("");
            var idNum = "#JackepotNum" + index;
            $(idNum).html("");
            $.ajax({
                type: "post",
                url: '/Market/JackpotBox',
                data: { type: type },
                success: function (data) {
                    var $option = "";
                    if (data.length > 0) {
                        $option += "<option value='0' data-num='0'    >---请选择---</option>";
                        for (var i = 0; i < data.length; i++) {
                            if (boxVal != 0 && boxVal == data[i].Id) {
                                $option += "<option value='" + data[i].Id + "' data-num='" + data[i].ResidueNums + "' selected    >" + data[i].Name + "</option>";
                                $(idNum).text(data[i].ResidueNums).css('color', '#43A63A');
                                boxValArr.push(boxVal);
                            }
                            else {
                                //判断奖项是否被用过
                                var b = true;
                                for (var j = 0; j < boxValArr.length; j++) {
                                    if (boxValArr[j] == data[i].Id) {
                                        b = false;
                                        break;
                                    }
                                }
                                if (b) {
                                    if (oper == "add" && i == 0) {
                                        $option += "<option value='" + data[i].Id + "' data-num='" + data[i].ResidueNums + "'  selected='selected'   >" + data[i].Name + "</option>";
                                    }
                                    else
                                        $option += "<option value='" + data[i].Id + "' data-num='" + data[i].ResidueNums + "'    >" + data[i].Name + "</option>";
                                }
                            }
                        }
                    }
                    else {
                        $option += "<option value='0' data-num='0'    >---暂无数据---</option>";
                    }
                    $(id).html($option);
                    $.MGJ.TableEggsActivity.GetAwardNum(index);
                }
            })
        },
        //改变奖项类型
        changeJackpotType: function (ele, index) {
            var type = $(ele).val();
            $.MGJ.TableEggsActivity.GetAward(type, index);
            if (type == 1) {
                $('#AwName').text('微信红包2元');
            }
            else if (type == 2) {
                $('#AwName').text('10元天猫优惠券');
            }
            else if (type == 3) {
                $('#AwName').text('2元流量券');
            }
        },
        //奖项切换事件
        SkipTab: function (num, oper) {
            oper = oper || "add";
            pageTabIndex = num;
            //清空奖项详细界面显示
            $.MGJ.TableEggsActivity.clearPage()
            //赋值奖项详细界面显示
            $.MGJ.TableEggsActivity.valuePage(num);
            //奖项类型  奖项索引  下拉框选中的索引
            $.MGJ.TableEggsActivity.GetAward($("#JackpotType" + pageTabIndex).val(), pageTabIndex, $("#JackpotID" + pageTabIndex).val(), oper);
            $(".AwardTab").hide();
            $("#Award0" + num).show();
        },
        //清空奖项详细界面显示
        clearPage: function() {
            $("#Congrats1").text("");
            $("#handleTips").text("");
            $("#ServicePhone").text("");
            $("#defindBtn").text("");
            $(".DefineBtnTypeClose,.DefineBtnAll").hide();
        },
        //赋值奖项详细界面显示
        valuePage: function(num) {
            $("#Congrats1").text($("#Name" + num).val())
            $("#handleTips").text($("#point" + num).val())
            $("#ServicePhone").text($("#ServicePhone" + num).val())
            $("#defindBtn").text($("#ButtonName" + num).val())

            //自定义按钮
            if ($("#defineClose" + num).is(":checked")) {//关闭 状态
                $("#DefineBtnLink").hide();
            }
            else if ($("#defineClose" + num).is(":checked")) {//页面跳转 状态
                $("#DefineBtnLink").show();
            }
            else {// 一键关注 状态
                $("#DefineBtnLink").show();
            }
            //奖项自定义按钮赋值 单选框
            var ButtonType = $('#Award0' + num + ' input:radio[name="ButtonType"]:checked').val();
            if (ButtonType == "0") IsShow(0, ".DefineBtnTypeClose" + num + ",.DefineBtnTypeClose");
            else if (ButtonType == "1") IsShow(1, ".DefineBtnLink" + num + ",.DefineBtnLink", ".DefineBtnAll");
            else if (ButtonType == "2") IsShow(2, ".DefineBtnAll" + num + ",.DefineBtnAll", ".DefineBtnLink");
        },
        //保存
        Ajax_Save: function () {
            sessionStorage.removeItem('alertSave');
            sessionStorage.removeItem('isFirst');
            sessionStorage.removeItem('isLeave');

            //$("#finalSave").attr("disabled", true);
            // 遍历全部奖项   把数据保存到对象
            $('.clickEdict').css('display', 'none');
            $('.ui-resizable-handle').remove();
            var AwardsData = [];
            var sumNum = 0;
            for (var i = 1; i <= pageCount; i++) {
                //检查奖项数量是否大于批次数量  中奖率是否为百分比
                sumNum += parseInt($("#TotalNums" + i).val());
                var AwardFrom_formValidator = $("#Award0" + i).data('bootstrapValidator').validate();
                if (AwardFrom_formValidator.isValid()) {
                    var data = $("#Award0" + i).serializeObject();
                    AwardsData.push($("#Award0" + i).serializeObject());
                }
                else {
                    $.L.msgError("请检查数据格式！");
                    return;
                }
            }
            if (AwardsData.length <= 0) {
                $.L.msgError("奖项不能为空！");
                return;
            }
            if (sumNum > $("#batchNum").text()) {
                AwardsData.length = 0;
                $.L.msgWarning("累计奖项数量大于批次数量！");
                return;
            }
            var b = new this.Base64();
            var template = {
                ID: $("#TemId").val(),
                ActivityHome: b.encode($("#red1").html()),//首页
                ActivityRuleState: b.encode($("#red2 .bg-con").html()),//活动说明规则 
                MyPrizeRecord: b.encode($("#red3").html()),//中奖记录
                PrizeDetailsShow: b.encode($("#red4").html()),//奖品明细
                Verification: b.encode($("#red5").html()),//手机验证
                GetSucceed: b.encode($("#red6 .bg-con").html()),//中奖页面
                GetError: b.encode($("#red7 .bg-con").html()),//没中奖页面
                GetYet: b.encode($("#red8 .bg-con").html()),//奖品被领取
                GetInForm: b.encode($("#red9").html()),//奖品领取完成
                NotStart: b.encode($("#red10").html()),//活动未开始
            }
            var activity_form = $("#activity_form").serializeObject();
            if ($("#IsLimitArea").val() == 1) {
                activity_form["Privance"] = $("#Privance").val() == null ? " " : $("#Privance").val().join(",");
                activity_form["City"] = $("#City").val() == null ? " " : $("#City").val().join(",");
            }
            var delivery_form = $("#delivery_form").serializeObject();
            var activityInfo_form = $("#activityInfo_form").serializeObject();

            var data = JSON.stringify({
                template: template,
                activity: activity_form,
                delivery: delivery_form,
                awardsList: AwardsData,
                webInfo: activityInfo_form,
            });
            var batchInput = $("#batchInput").val();
            if (batchInput == "@Model.activity.Batch") {
                $.L.msgError("请填写生码批次！");
            }
            else {
                if ($(event.target).attr("id") != "batch") {
                    $.ajax({
                        url: ACTION_URL("ActivityAdd", "Market"),
                        contentType: "application/json",
                        type: "POST",
                        datatype: "json",
                        data: data,
                        success: function (data) {
                            if (data == true) {
                                $.MGJ.Common.loadurl(this, '/Market/ActivitiesManage');
                                $.L.msgSuccess('保存成功！');
                            }
                            else $.L.msgError("保存失败，可能原因：" + data);
                            $("#finalSave").attr("disabled", false);
                        }
                    })
                }
                else {
                    return
                }
            }
        },
        //编辑页面时初始化
        Ajax_Initialization: function (obj) {
            $("#red1").html("");
            $("#red2  .bg-con").html("");
            $("#red3").html("");
            $("#red4").html("");
            $("#red5").html("");
            $("#red6  .bg-con").html("");
            $("#red7  .bg-con").html("");
            $("#red8  .bg-con").html("");
            var b = new this.Base64();
            $.L.ajaxHandle({
                url: ACTION_URL("GetTemplate", "Market") + "?aId=" + obj,
                success: function (response) {
                    if (response) {
                        $("#TemId").val(response.ID);
                        $("#red1").html(b.decode(response.ActivityHome));
                        $("#red2  .bg-con").html(b.decode(response.ActivityRuleState));
                        $("#red3").html(b.decode(response.MyPrizeRecord));
                        $("#red4").html(b.decode(response.PrizeDetailsShow));
                        $("#red5").html(b.decode(response.Verification));
                        $("#red6  .bg-con").html(b.decode(response.GetSucceed));
                        $("#red7  .bg-con").html(b.decode(response.GetError));
                        $("#red8  .bg-con").html(b.decode(response.GetYet));
                    }
                    $('.clickEdict').removeAttr('style');
                    //可拖可拽
                    $('.resizable.draggable').resizable({
                        containment: 'parent',
                        stop: function (e,ui) {
                            var parentW = $(this).parent().width();
                            var parentH = $(this).parent().height();
                            var _thisW = $(this).width();
                            var _thisH = $(this).height();
                            var left = parseInt($(this).css('left'));
                            var top = parseInt($(this).css('top'));
                            $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
                        }
                    });
                    $('.resizable.draggable').draggable({
                        containment: 'parent',
                        stop: function () {
                            var parentW = $(this).parent().width();
                            var parentH = $(this).parent().height();
                            var _thisW = $(this).width();
                            var _thisH = $(this).height();
                            var left = parseInt($(this).css('left'));
                            var top = parseInt($(this).css('top'));
                            $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
                        }
                    });
                    $('.draggable').draggable({
                        containment: 'parent',
                        stop: function () {
                            var parentW = $(this).parent().width();
                            var parentH = $(this).parent().height();
                            var _thisW = $(this).width();
                            var _thisH = $(this).height();
                            var left = parseInt($(this).css('left'));
                            var top = parseInt($(this).css('top'));
                            $(this).css({ 'left': ((left / parentW) * 100).toFixed(2) + '%', 'top': ((top / parentH) * 100).toFixed(2) + '%', 'width': ((_thisW / parentW) * 100).toFixed(2) + '%', 'height': ((_thisH / parentH) * 100).toFixed(2) + '%' });
                        }
                    });
                }
            });
        },
        Base64: function (input) {
            _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            // public method for encoding
            this.encode = function (input) {
                var output = "";
                if (input == null) return output;
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;
                input = _utf8_encode(input);
                while (i < input.length) {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);
                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;
                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }
                    output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
                }
                return output;
            }
            // public method for decoding
            this.decode = function (input) {
                var output = "";
                if (input == null) return output;
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
                while (i < input.length) {
                    enc1 = _keyStr.indexOf(input.charAt(i++));
                    enc2 = _keyStr.indexOf(input.charAt(i++));
                    enc3 = _keyStr.indexOf(input.charAt(i++));
                    enc4 = _keyStr.indexOf(input.charAt(i++));
                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;
                    output = output + String.fromCharCode(chr1);
                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }
                }
                output = _utf8_decode(output);
                return output;
            }
            // private method for UTF-8 encoding
            _utf8_encode = function (string) {
                string = string.replace(/\r\n/g, "\n");
                var utftext = "";
                for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n);
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    } else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    } else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                }
                return utftext;
            }
            // private method for UTF-8 decoding
            _utf8_decode = function (utftext) {
                var string = "";
                var i = 0;
                var c = c1 = c2 = 0;
                while (i < utftext.length) {
                    c = utftext.charCodeAt(i);
                    if (c < 128) {
                        string += String.fromCharCode(c);
                        i++;
                    } else if ((c > 191) && (c < 224)) {
                        c2 = utftext.charCodeAt(i + 1);
                        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                        i += 2;
                    } else {
                        c2 = utftext.charCodeAt(i + 1);
                        c3 = utftext.charCodeAt(i + 2);
                        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                        i += 3;
                    }
                }
                return string;
            }
        }
    })
})(jQuery)

 
   

//计算中奖率  数量元素  奖项索引
function CalcRate(ele,index)
{
    var BatchNum = parseInt($('#batchNum').text());//批次数量
    var JackepotNum = parseInt($('#JackepotNum'+index).text()); //奖品可用数量 
    var AwardNum = parseInt($(ele).val())||0;//中奖数量

    if (AwardNum <= BatchNum && AwardNum <= JackepotNum) {
        var AwardRate = (AwardNum / BatchNum);//中奖率
        $(ele).parent().parent().next().find('input[name="Rate"]').val((AwardRate * 100).toFixed(2));
    }
    //else if ($(ele).val() == '')
    //{
    //    $.L.msgError('中奖数量不能空 ');
    //}
    //else if (AwardNum < 0) {
    //    $.L.msgError('中奖数量不能小于0 ');
        //}
    //else if (BatchNum=="0") {
    //    $.L.msgWarning("请先选择批次!");
    //    return false;
    //}
    else {
        $.L.msgWarning('中奖数量不能大于批次数量 ' + BatchNum + '和奖品可用数量' + JackepotNum);
        $(ele).val("");
        return false;
    }
    return true;
}
//判断有无选择批次
function judge(ele) {
    var BatchNum = parseInt($('#batchNum').text());//批次数量
    if (BatchNum=="0") {
        $.L.msgWarning("请先选择批次!");
        $("#level2>li:nth-child(3)").removeClass("active")
        $("#level2>li:nth-child(1)").addClass("active")
        $("#award1").addClass("in active")
        $("#award3").removeClass("in active")
    }
    else {
        return;
    }
}

//绑定双向数据
function doubleBind(ele,bindele)
{
    if (bindele == '#defindBtn' || bindele == '#FunctionLink' || bindele == '#FinishFunctionLink')
    {
        $(bindele).attr('href',$(ele).val());
        return;
    }
    $('#' + bindele).text($(ele).val());
}

function doubleGradeBind(ele,j)
{
    $("#img" + j).parent(".img").next().text($(ele).find("option:selected").text());
}
//绑定奖项名称
//function doubleAwardsBind(ele,bindele)
//{
//    $(bindele).text($(ele).val());
//}

//绑定双向title数据
//function doubleBindTitle(el) {
//    $('.phoneView.active').find('.pageTitle > span').text($(el).val());
//}





//校验基础数据
$('#activity_form').bootstrapValidator({
    group: '.forTime',
    fields: {
        Title: {
            validators: {
                notEmpty: {
                    message: '标题不能为空'
                },
            }
        },
        StartDate: {
            validators: {
                notEmpty: {
                    message: '开始时间不能为空'
                },
            }
        },
        EndDate: {
            validators: {
                notEmpty: {
                    message: '结束时间不能为空'
                },
            }
        },
        RuleExplain: {
            validators: {
                notEmpty: {
                    message: '活动规则不能为空'
                },
            }
        },
    }
});
//校验派奖方式
$('#delivery_form').bootstrapValidator({
    //group: '.forTime',
    fields: {
        EachGetSumNum: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
            }
        },
        DayGetPrizeNum: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
            }
        },
        EachGetPrizeNum: {
            validators: {
                notEmpty: {
                    message: '不能为空'
                },
            }
        },
    }
});
//校验奖项设置(抢红包)
$('#Award0_form').bootstrapValidator({
    //group: '.forTime',
    fields: {
        Name: {
            validators: {
                notEmpty: {
                    message: '奖品名称不能为空'
                },
            }
        },
        TotalNums: {
            validators: {
                notEmpty: {
                    message: '奖品数量不能为空'
                },
                regexp: {
                    regexp: /^[1-9]\d*$/,
                    message: '奖品数量为正整数'
            }
            }
        },
        Congrats: {
            validators: {
                notEmpty: {
                    message: '操作提示不能为空'
                },
            }
        },
    }
});
//校验奖项设置(大转盘)
for (var i = 1; i <= 8; i++) {
    $("#Award0" + i).bootstrapValidator({
        fields: {
            Name: {
                validators: {
                    notEmpty: {
                        message: '奖品名称不能为空'
                    },
                }
            },
            TotalNums: {
                validators: {
                    notEmpty: {
                        message: '奖品数量不能为空'
                    },
                    regexp: {
                        regexp: /^\+?[1-9][0-9]*$/,
                        message: '奖品数量为正整数'
                    }
                }
            },
            Congrats: {
                validators: {
                    notEmpty: {
                        message: '操作提示不能为空'
                    },
                }
            }
        }
    })
}

//派奖方式
$("#oneChance").blur(function () {
    var all = $("#allChance").val()
    var one = $("#oneChance").val()
    if (all!=''&&one!='') {
        var num = all - one
        if (num < 0) {
            $.L.msgError('总抽奖机会必须大于每人中奖次数！');
        }
    }
})
$("#dayChance").blur(function () {
    var all = $("#allChance").val()
    var day = $("#dayChance").val()
    if (all != '' && day != '') {
        var num = all - day
        if (num < 0) {
            $.L.msgError('总抽奖机会必须大于每日抽奖机会！');
        }
    }
})


function VerifyAwardFrom()
{
    var totalRate = 0;
    for (var i = 1; i <= pageCount; i++) {
        //计算中奖率  数量元素  奖项索引
        if (!CalcRate("#TotalNums" + i, i)) {
            return false;
        } 
        totalRate +=parseFloat( $("#Rate" + i).val());
    }
    if (totalRate > 100) {
        $.L.msgError("中奖率超出100%！");
        return false;//中奖率超出100%
    }
    return true;
}

//单个表单校验
//function formCheck(ele) {
//    var formCheck = $(ele).parents('.formCheck').data('bootstrapValidator').validate();
//    var batchInput = $("#batchInput").val();
//    if (formCheck.isValid() && batchInput != "@Model.activity.Batch") {
//        $('#level2 > li').each(function (index, ele) {
//            $(this).find('a').removeAttr('onclick').attr({ 'href': '#award' + (index + 1), 'data-toggle': 'tab' });
//        })
//        $('#finalSave').removeAttr('disabled');
//    }
//    else {
//        $('#level2 > li.active').siblings('li').find('a').removeAttr('href data-toggle').attr('onclick', 'formCheckTips()');
//        $('#finalSave').attr('disabled', 'disabled');
//    }
//}
//function formCheckTips() {
//    $.L.msgError("请检查数据格式!");
//}









$("#StartDate").datepicker({
    format: "yyyy-mm-dd",
    language: 'cn',
    todayBtn: "linked",
    orientation: 'bottom',
    autoclose: true,
    todayHighlight: true
}).on('hide', function (e) {
    $('#activity_form').data('bootstrapValidator')
        .updateStatus('StartDate', 'NOT_VALIDATED', null)
        .validateField('StartDate');
}).on('changeDate', function (e) {
    var startTime = e.date;
    $('#EndDate').datepicker('setStartDate', startTime);
    //formCheck("#StartDate")
});
$("#EndDate").datepicker({
    format: "yyyy-mm-dd",
    language: 'cn',
    todayBtn: "linked",
    orientation: 'bottom',
    autoclose: true,
    todayHighlight: true
}).on('hide', function (e) {
    $('#activity_form').data('bootstrapValidator')
        .updateStatus('EndDate', 'NOT_VALIDATED', null)
        .validateField('EndDate');
}).on('changeDate', function (e) {
    var endTime = e.date;
    $('#StartDate').datepicker('setEndDate', endTime);
    //formCheck("#EndDate")
});

$("#vailStartDate").datepicker({
    format: "yyyy-mm-dd",
    language: 'cn',
    todayBtn: "linked",
    orientation: 'bottom',
    autoclose: true,
    todayHighlight: true
}).on('changeDate', function (e) {
    var startTime = e.date;
    $('#vailEndDate').datepicker('setStartDate', startTime);
});

$("#vailEndDate").datepicker({
    format: "yyyy-mm-dd",
    language: 'cn',
    todayBtn: "linked",
    orientation: 'bottom',
    autoclose: true,
    todayHighlight: true
}).on('changeDate', function (e) {
    var endTime = e.date;
    $('#vailStartDate').datepicker('setEndDate', endTime);
});
